import DocumentTitle from 'react-document-title';
import Router,{Route,Link} from 'preact-router';
import loadRouter from '@/boot/loadRouter'
import queryString from 'query-string';
import './index.scss'
import { useState } from 'preact/hooks';
export function CRouter() {
  let [showTab,setShowTab] = useState(true);
  let [tabs,setTabs] = useState(loadRouter.tabs);
  console.log(tabs);
  const handleRoute=async(e:any)=>{
    console.log(e);
    let dataTabs=[...tabs];
    dataTabs.forEach(item=>{
      item.active = false;
      if(item.path==e.url){
        item.active = true;
      }
    })
    setTabs(dataTabs);
    console.log(tabs);
  }
  return (
    <>
        <Router onChange={handleRoute}>
          {
            [...loadRouter.other,...loadRouter.tabs].map((r:any) => {
              const Component = r.component;
              return (
                  <Route
                      key={r.path || r.path}
                      exact
                      path={r.path || r.path}
                      component={(props:any) => {
                          const queryParams = props.matches;
                          const merge = {
                              ...props,
                              query: queryParams
                                  ? queryString.parse(queryParams)
                                  : {},
                          };
                          // 重新包装组件
                          const wrappedComponent = (
                              <DocumentTitle title={r.meta.title}>
                                  <Component {...merge} />
                              </DocumentTitle>
                          );
                          return wrappedComponent;
                        }
                      }
                  />
              );
            })
          }
        </Router>
        {showTab?<div class='route_tabbox'>
          {tabs.map((item:any)=>{
            return(
              <span key={item.path} className={item.active?'selecttabitem':'tabitem'}><Link href={item.path}>{item.meta.title}</Link></span>
            )
          })}
        </div>:null}
    </>  
  )
}